package pl.mchaniewski.ryneczek.services.impl;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pl.mchaniewski.ryneczek.dao.IndexDao;
import pl.mchaniewski.ryneczek.pojo.Company;
import pl.mchaniewski.ryneczek.pojo.Index;
import pl.mchaniewski.ryneczek.services.IndexService;

@Service("indexService")
public class IndexServiceImpl implements IndexService {
    private static final Logger logger = LoggerFactory
            .getLogger(IndexServiceImpl.class);
    private IndexDao indexDao;

    @Autowired
    public void setIndexDao(IndexDao indexDao) {
        this.indexDao = indexDao;
    }

    @Override
    public Index save(Index entity) {
        try {
            return indexDao.save(entity);
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }
    }

    @Override
    public boolean remove(Index entity) {
        try {
            indexDao.remove(entity);
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return false;
        }

        return true;
    }

    @Override
    public List<Index> findAll() {
        try {
            return indexDao.loadAll();
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }
    }

    @Override
    public Index findByName(String name) {
        List<Index> indexList;
        try {
            indexList = indexDao.findByName(name);
        } catch (Exception ex) {
            logger.error("Exception: {}", ex.getMessage());

            return null;
        }

        if (indexList == null || indexList.size() == 0) {
            return null;
        }

        if (indexList.size() > 1) {
            logger.warn("Two or more indices with same name! Name: {})",
                    indexList.get(0).getName());
        }

        return indexList.get(0);
    }

    @Override
    public Index createNewIndex(String name) {
        Index newIndex = new Index();
        newIndex.setName(name);

        return save(newIndex);
    }

    @Override
    public boolean isCompanyInIndex(String[] indices, Company company) {
        List<String> indexList = Arrays.asList(indices);
        for (Iterator<Index> it = company.getIndexes().iterator(); it.hasNext();) {
            String indexName = it.next().getName();
            if (indexList.contains(indexName)) {
                return true;
            }
        }

        return false;
    }

}
